package net.myspring.common.config;

import net.myspring.common.thymeleaf.function.dialect.ThymeleafFunctionDialect;
import net.myspring.common.utils.Const;
import net.myspring.common.web.TokenInterceptor;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;

import java.util.Locale;

/**
 * Created by liuj on 2016-07-18.
 */
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    /**
     * Thymeleaf LocaleResolver
     */
    @Bean
    public LocaleResolver localeResolver() {
        CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
        cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH);
        cookieLocaleResolver.setCookieMaxAge(10 * 365 * 24 * 60 * 60);
        cookieLocaleResolver.setCookieName("lang");
        return cookieLocaleResolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        registry.addInterceptor(localeChangeInterceptor);
        registry.addInterceptor(new MyHandlerInterceptor());
        registry.addInterceptor(new TokenInterceptor());
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasenames("classpath:/i18n/messages");
        messageSource.setDefaultEncoding(Const.CharEnum.UTF8.getValue());
        return messageSource;
    }


    @Bean
    public ThymeleafFunctionDialect domainCacheDialect() {
        return new ThymeleafFunctionDialect();
    }

    /**
     * Joda Time to Thymeleaf converter<br>
     * Spring Boot, in the ThymeleafAutoConfiguration class,
     * will automatically add any Beans that implement the IDialect interface.
     */
    @Bean
    public Java8TimeDialect java8TimeDialect() {
        return new Java8TimeDialect();
    }

    /**
     * Thymeleaf - Spring Security Integration
     */
    @Bean
    public SpringSecurityDialect springSecurityDialect() {
        return new SpringSecurityDialect();
    }

}
